<?php
defined('_VALID') or die('Restricted Access!');

require $config['BASE_DIR']. '/classes/filter.class.php';
require $config['BASE_DIR']. '/classes/validation.class.php';
require $config['BASE_DIR']. '/classes/email.class.php';
require $config['BASE_DIR']. '/classes/file.class.php';
require $config['BASE_DIR']. '/include/compat/json.php';
require $config['BASE_DIR']. '/include/adodb/adodb.inc.php';
require $config['BASE_DIR']. '/include/dbconn.php';

disableRegisterGlobals();

function clean( $string )
{
    $string = ereg_replace('[^ 0-9a-zA-Z]', ' ', $string);
    $string = preg_replace('/\s\s+/', ' ', $string);
    $string = trim($string);
    $string = str_replace(' ', '-', $string);

    return strtolower($string);
}

$data   = array('status' => 0, 'msg' => '', 'debug' => '');
if ( isset($_POST['item_id']) ) {
    $filter     = new VFilter();
    $video_id   = $filter->get('item_id', 'INTEGER');
    $from       = $filter->get('from');
    $to         = $filter->get('to');
    
     // Edit by thoinv{
    // Nếu người dùng nhập vào thừa số ký tự đã quy định thì cắt bớt đi
    
    $message    = ereg_replace( "\n", '', $filter->get('message')); 
                    
    if(strlen($message) >= 200){
      $message    = substr( ereg_replace( "\n", '', $filter->get('message')), 0, 300);
    }
    
    //}
       
    
    $uid		= $filter->get('uid');
	$mls		= $filter->get('mls');
	$share_title= $filter->get('share_title');
	$price		= $filter->get('price');
    $from       = ereg_replace('[^ 0-9a-zA-Z,@.]', '', $from);
    $to         = ereg_replace('[^ 0-9a-zA-Z,@.]', '', $to);
    $to         = str_replace(',', '', $to);
    $to         = preg_replace('/\s\s+/', ' ', $to);
    $to         = str_replace("\r", '', $to);
    $to         = str_replace("\n", '', $to);
    $to         = explode(' ', $to);
    if ( !$to ) {
        $data['msg']    = $lang['ajax.share_recipient'];
    } else {
        $emails         = array();
        $users          = array();
        $valid          = new VValidation();
        foreach ( $to as $key => $value ) {
            if ( $valid->email($value) ) {
                $emails[]   = $value;
            } elseif ( $valid->usernameExists($value) ) {
                $users[]    = $value;
            }
        }
        
        if ( $users ) {
            $sql_add    = array();
            foreach ( $users as $user ) {
                $sql_add[] = "'" .mysql_real_escape_string($user). "'";
            }
            $sql            = "SELECT email FROM signup WHERE username IN (" .implode(',', $sql_add). ")";
            $rs             = $conn->execute($sql);
            $users_emails   = $rs->getrows();
            foreach($users_emails as $user) {
                $emails[] = $user['email'];
            }
        }
        
        if ( !$emails ) {
            $data['msg']    = $lang['ajax.share_recipient_valid'];
        } else {
            $ShareTitleSplit = explode(',', $share_title);
        	$sql_user			= "SELECT * FROM signup WHERE UID = '" .$uid. "' LIMIT 1";
			$rs_user            = $conn->execute($sql_user);
			$u_photo			= $rs_user->fields['photo'];
            
            //Add by thoinv 
            // Nếu người dùng chưa upload avatar thì sử dụng avatar mặc định {
            $gender            = $rs_user->fields['gender'];    
            $url_photo            = $u_photo == ''? $config['BASE_URL']."/media/users/". (
                                                        $gender == "Male"? "nopic-Male.gif" : "nopic-Female.gif" // Hiển thị avatar theo giới tính
                                                    )
                                                  : $config['BASE_URL']."/media/users/".$u_photo;
            $photo_user         = "<img style='border: 3px solid #ccc;float:left;margin:12px 14px 12px 5px' width='33%' src='".$url_photo.""."' />";//Edit by thoinv
            
            //}
            
			$full_name			= $rs_user->fields['fname']." ".$rs_user->fields['lname'];
			$company			= $rs_user->fields['company'];
			$email				= $rs_user->fields['email'];
			$adrees				= $rs_user->fields['city']."-".$rs_user->fields['country'];
			$phone				= $rs_user->fields['phone'];
			$fax				= $rs_user->fields['fax'];
			$facebook			= $rs_user->fields['facebook'];
			$twitter			= $rs_user->fields['twitter'];
			$skype  			= $rs_user->fields['skype'];
			$website			= $rs_user->fields['website'];
			$zillow_id			= $rs_user->fields['zillow_id'];
			
            $sql                = "SELECT * FROM video WHERE VID = " .$video_id. " LIMIT 1";
            $rs                 = $conn->execute($sql);
			$embed				= $rs->fields['embed_code'];
			
			$sql_ads 			= "SELECT * FROM ads_code WHERE id = 1";
			$rs         		= $conn->execute($sql_ads);
			$code_ads 			= $rs->fields['code'];
        
			//API
			$xml = simplexml_load_file("http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=$zillow_id&address=".$ShareTitleSplit[0]."&citystatezip=".$ShareTitleSplit[1]);
            
            //echo "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=$zillow_id&address=".$ShareTitleSplit[0]."&citystatezip=".$ShareTitleSplit[1];
            //print_r($xml);
            
            $url_zillow     = $xml->response->results->result->links->homedetails;
            $adrees_home    = $xml->response->results->result->links->address->street;
            $city           = $xml->response->results->result->links->address->city;
            $state          = $xml->response->results->result->links->address->state;
            $zipcode        = $xml->response->results->result->links->address->city;
            $full_adress    = $adrees_home." , ".$city." , ".$state." , ".$zipcode;
            
            $type     = $xml->response->results->result->useCode;
            
            $beds           = $xml->response->results->result->bedrooms;
            $bath           = $xml->response->results->result->bathrooms;
            $yearBuilt      = $xml->response->results->result->yearBuilt;
            $finishedSqFt   = $xml->response->results->result->finishedSqFt;
            $lotSizeSqFt    = $xml->response->results->result->lotSizeSqFt;
            
            
            $TaxHistory     = $xml->response->results->result->taxAssessment;
            $TaxHistory_y   = $xml->response->results->result->taxAssessmentYear;
            $TaxHistory     = number_format("$TaxHistory");
            $lastSoldDate   = $xml->response->results->result->lastSoldDate;
            $lastSoldPrice  = $xml->response->results->result->lastSoldPrice;
            $lastSoldPrice  = number_format("$lastSoldPrice");
			//$price			= $xml->response->properties->principal->zestimate->amount;
			
			$homedetails	 ="<h2 style='background:green;padding: 3px;float:left;width:100%;margin:0'><a style='float: right;text-decoration: none;color: #FFFFFF;font-size:18px' href='$url_zillow'>$share_title</a></h2>";
			$homedetails	.="<h3 style='padding: 2px;float:left;width:100%;margin:0;text-align:left'>Price :$ $price</h3>";
			$homedetails	.="<table width='100%' style='font-size: 12px;float:right;' >";
			
			$homedetails	.="<tr>";
			$homedetails	.="<td>Beds: ".$beds."</td>";
			$homedetails	.="<td>Baths:  ".$bath."</td>";
			$homedetails	.="</tr>";
			
			$homedetails	.="<tr>";
			$homedetails	.="<td>Sqft: ".$finishedSqFt."</td>";
			$homedetails	.="<td>Lot: ".$lotSizeSqFt." sq ft </td>";
			$homedetails	.="</tr>";
			
			$homedetails	.="<tr>";
			$homedetails	.="<td>Year Built: ".$yearBuilt."</td>";
			$homedetails	.="<td>Type: ".$type."</td>";
			$homedetails	.="</tr>";
			
			$homedetails	.="<tr>";
			$homedetails	.="<td>Tax History $: ".$TaxHistory." (".$TaxHistory_y.") </td>";
			$homedetails	.="<td>Price History $: ".$lastSoldPrice." (".$lastSoldDate.") </td>";
			$homedetails	.="</tr>";
			
			$homedetails	.="</table>";
			
			
			// $homedetails	.="<p>Beds: ".$beds."</p>";
			// $homedetails	.="<p>Baths:  ".$bath."</p>";
			// $homedetails	.="<p>Sqft: ".$finishedSqFt."</p>";
			// $homedetails	.="<p>Lot: ".$lotSizeSqFt."</p>";
			// $homedetails	.="<p>Year Built: ".$yearBuilt."</p>";
			
			
			
			
			//$embed = '<iframe width="560" height="315" src="http://www.youtube.com/embed/S5zfx5zCUwQ" frameborder="0" allowfullscreen></iframe>';
            if ( $conn->Affected_Rows() == 1 ) {
                
                $sql                = "SELECT * FROM video WHERE VID = " .$video_id. " LIMIT 1";
                $rs                 = $conn->execute($sql);
                
            	$logo			= $config['BASE_URL']."/templates/frontend/".$config['template']."/images/logo.png";
                $title          = $rs->fields['title'];
                $url            = $config['BASE_URL']. '/video/' .$video_id. '/' .clean($title);
				$url_img		= $config['BASE_URL']."/media/videos/tmb/".$video_id."/".$rs->fields['thumb'].".jpg";
                $sql            = "SELECT email_subject, email_path FROM emailinfo
                                   WHERE email_id = 'share_video' LIMIT 1";
                $rs             = $conn->execute($sql);
                $email_subject  = str_replace('{$sender_name}', $from, $rs->fields['email_subject']);
                $email_path     = $config['BASE_DIR']. '/templates/' .$rs->fields['email_path'];
                $body           = VFile::read($email_path);
                $body           = str_replace('{$site_name}', $config['site_name'], $body);
                $body           = str_replace('{$video_link}', $url, $body);
                $body           = str_replace('{$sender_name}', $from, $body);
                $body           = str_replace('{$message}', $message, $body);
				$body           = str_replace('{$embed}', $embed, $body);
				$body           = str_replace('{$photo_user}', $photo_user, $body);
				$body           = str_replace('{$full_name}', $full_name, $body);
				$body           = str_replace('{$company}', $company, $body);
				$body           = str_replace('{$email}', $email, $body);
				$body           = str_replace('{$adrees}', $adrees, $body);
				$body           = str_replace('{$title}', $title, $body);
				$body           = str_replace('{$logo}', $logo, $body);
				$body           = str_replace('{$url}', $url, $body);
				$body           = str_replace('{$url_img}', $url_img, $body);
				$body           = str_replace('{$baseurl}', $config['BASE_URL'], $body);
				
				$body           = str_replace('{$phone}', $phone, $body);
				$body           = str_replace('{$fax}', $fax, $body);
				$body           = str_replace('{$facebook}', $facebook, $body);
				$body           = str_replace('{$twitter}', $twitter, $body);
				$body           = str_replace('{$skype}', $skype, $body);
				$body           = str_replace('{$website}', $website, $body);
				
				$body           = str_replace('{$homedetails}', $homedetails, $body);
				
				$body           = str_replace('{$share_title}', $share_title, $body);
				$body           = str_replace('<br>','', $body);
                
                  /* Add by thoinv 
                 * 
                 * Text ads trên email mà người dùng nhận được
                 * */
                $text_ads_path     = $config['BASE_DIR']. '/templates/emails/text_ads_on_email.tpl';
                $code_ads_on_email           = VFile::read($text_ads_path);
                $body           = str_replace('{$code_ads_on_email}', $code_ads_on_email, $body);
				
				$body           = str_replace('{$code_ads}',$code_ads, $body);
                
                
                
               /* echo $code_ads;*/
				//echo $body;
			
                $mail           = new VMail();
                $mail->setNoReply();
                $mail->Subject  = $email_subject;
                $mail->AltBody  = $body;
                $mail->Body     = nl2br($body);
                foreach ( $emails as $email ) {
                    $mail->AddAddress($email);
                    $mail->Send();
                    $mail->ClearAddresses();
                }
                $data['status'] = 1;
                $data['msg']    = $lang['ajax.share_success'];
            } else {
                $data['msg']    = $lang['ajax.share_video_failed'];
            }
        }
    }
}

echo json_encode($data);
die();
?>